<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="PragmaticScala">
<meta name="generator" content="Paradox, paradox-material-theme=0.5.1, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="PragmaticScala">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>第3章——从Java到Scala · </title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
</span>
<span class="md-header-nav__topic">
第3章——从Java到Scala
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="">
</a>
</label>
<ul>
  <li><a href="../contents.html" class="page">目录</a>
  <ul>
    <li><a href="../abstract.html" class="page">内容提要</a></li>
    <li><a href="../part1.html" class="page">第一部分 小试牛刀</a></li>
    <li><a href="../part2.html" class="page">第二部分 深入 Scala</a></li>
    <li><a href="../part3.html" class="page">第三部分 Scala 中的并发编程</a></li>
    <li><a href="../part4.html" class="page">第四部分 Scala 实战</a></li>
    <li><a href="../refs/references.html" class="page">参考书目</a></li>
    <li><a href="../extras.html" class="page">额外指引</a></li>
    <li><a href="../errata.html" class="page">勘误</a></li>
  </ul></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-03/index.html#第3章-从java到scala" class="header">第3章——从Java到Scala</a>
  <ul>
    <li><a href="../chapter-03/index.html#3-1-scala-简洁的-java" class="header">3.1 Scala：简洁的 Java</a></li>
    <li><a href="../chapter-03/index.html#3-2-java-原始类型对应的-scala-类" class="header">3.2 Java 原始类型对应的 Scala 类</a></li>
    <li><a href="../chapter-03/index.html#3-3-元组和多重赋值" class="header">3.3 元组和多重赋值</a></li>
    <li><a href="../chapter-03/index.html#3-4-灵活的参数和参数值" class="header">3.4 灵活的参数和参数值</a></li>
    <li><a href="../chapter-03/index.html#3-5-隐式参数" class="header">3.5 隐式参数</a></li>
    <li><a href="../chapter-03/index.html#3-6-字符串和多行原始字符串" class="header">3.6 字符串和多行原始字符串</a></li>
    <li><a href="../chapter-03/index.html#3-9-操作符重载" class="header">3.9 操作符重载</a></li>
    <li><a href="../chapter-03/index.html#3-10-scala-与-java-的差异" class="header">3.10 Scala 与 Java 的差异</a></li>
    <li><a href="../chapter-03/index.html#3-11-默认访问修饰符" class="header">3.11 默认访问修饰符</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-03/index.html#第3章-从java到scala" class="header">第3章——从Java到Scala</a>
  <ul>
    <li><a href="../chapter-03/index.html#3-1-scala-简洁的-java" class="header">3.1 Scala：简洁的 Java</a></li>
    <li><a href="../chapter-03/index.html#3-2-java-原始类型对应的-scala-类" class="header">3.2 Java 原始类型对应的 Scala 类</a></li>
    <li><a href="../chapter-03/index.html#3-3-元组和多重赋值" class="header">3.3 元组和多重赋值</a></li>
    <li><a href="../chapter-03/index.html#3-4-灵活的参数和参数值" class="header">3.4 灵活的参数和参数值</a></li>
    <li><a href="../chapter-03/index.html#3-5-隐式参数" class="header">3.5 隐式参数</a></li>
    <li><a href="../chapter-03/index.html#3-6-字符串和多行原始字符串" class="header">3.6 字符串和多行原始字符串</a></li>
    <li><a href="../chapter-03/index.html#3-9-操作符重载" class="header">3.9 操作符重载</a></li>
    <li><a href="../chapter-03/index.html#3-10-scala-与-java-的差异" class="header">3.10 Scala 与 Java 的差异</a></li>
    <li><a href="../chapter-03/index.html#3-11-默认访问修饰符" class="header">3.11 默认访问修饰符</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#第3章-从java到scala" name="第3章-从java到scala" class="anchor"><span class="anchor-link"></span></a>第3章——从Java到Scala</h1>
<p>你可以在使用 Scala 的同时运用自己的 Java 技能。在某些方面 Scala 与 Java 类似，但在 许多其他方面又彼此不同。Scala 青睐纯面向对象，但它又尽可能将类型和 Java 的类型对应 起来。Scala 在支持熟悉的命令式编程风格的同时，也支持函数式编程风格。因此，你可以使 用最熟悉的风格立即开始编程，而不用承受陡峭的学习曲线。</p>
<h2><a href="#3-1-scala-简洁的-java" name="3-1-scala-简洁的-java" class="anchor"><span class="anchor-link"></span></a>3.1 Scala：简洁的 Java</h2>
<blockquote>
  <p>FromJavaToScala/Greetings.java</p>
</blockquote>
<pre class="prettyprint"><code class="language-java">//Java code
public class Greetings {
  public static void main(String[] args) {
    for(int i = 1; i &lt; 4; i++) {
      System.out.print(i + &quot;,&quot;);     
    } 
    System.out.println(&quot;Scala Rocks!!!&quot;);
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Greetings.java#L19-L27">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">1,2,3,Scala Rocks!!!</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/Greetings.output#L2">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Greet.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">for (i ← 1 to 3) {
  print(s&quot;$i,&quot;)
}

println(&quot;Scala Rocks!!!&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Greet.scala#L21-L25">Full source at GitHub</a>
<p><em>运行结果</em></p>
<blockquote>
  <p>FromJavaToScala/Greet.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-output">1,2,3,Scala Rocks!!!</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/Greet.output#L2">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/GreetExclusiveUpper.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">for (i ← 1 until 3) {
  print(s&quot;$i,&quot;)
}

println(&quot;Scala Rocks!!!&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/GreetExclusiveUpper.scala#L21-L25">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">1,2,Scala Rocks!!!</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/GreetExclusiveUpper.output#L2">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/GreetForEach.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">(1 to 3).foreach(i ⇒ print(s&quot;$i,&quot;))

println(&quot;Scala Rocks!!!&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/GreetForEach.scala#L21-L23">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">1,2,3,Scala Rocks!!!</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/GreetForEach.output#L2">Full source at GitHub</a>
<h2><a href="#3-2-java-原始类型对应的-scala-类" name="3-2-java-原始类型对应的-scala-类" class="anchor"><span class="anchor-link"></span></a>3.2 Java 原始类型对应的 Scala 类</h2>
<blockquote>
  <p>FromJavaToScala/ScalaInt.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class ScalaInt {
  def playWithInt(): Unit = {
    val capacity: Int = 10
    val list = new java.util.ArrayList[String]
    list.ensureCapacity(capacity)
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/ScalaInt.scala#L20-L26">Full source at GitHub</a>
<h2><a href="#3-3-元组和多重赋值" name="3-3-元组和多重赋值" class="anchor"><span class="anchor-link"></span></a>3.3 元组和多重赋值</h2>
<blockquote>
  <p>FromJavaToScala/MultipleAssignment.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def getPersonInfo(primaryKey: Int) = {
  // Assume primaryKey is used to fetch a person&#39;s info...
  // Here response is hard-coded
  (&quot;Venkat&quot;, &quot;Subramaniam&quot;, &quot;venkats@agiledeveloper.com&quot;)
}

val (firstName, lastName, emailAddress) = getPersonInfo(1)

println(s&quot;First Name: $firstName&quot;)
println(s&quot;Last Name: $lastName&quot;)
println(s&quot;Email Address: $emailAddress&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/MultipleAssignment.scala#L21-L31">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">First Name: Venkat
Last Name: Subramaniam
Email Address: venkats@agiledeveloper.com</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/MultipleAssignment.output#L2-L4">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/MultipleAssignment2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def getPersonInfo(primaryKey: Int): (String, String, String) = {
  (&quot;Venkat&quot;, &quot;Subramaniam&quot;, &quot;venkats@agiledeveloper.com&quot;)
}

val (firstName, lastName) = getPersonInfo(1)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter3/MultipleAssignment2.scala#L21-L25">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">MultipleAssignment2.scala:5: error: constructor cannot be instantiated to
expected type;
 found   : (T1, T2)
 required: (String, String, String)
val (firstName, lastName) = getPersonInfo(1)
    ^
one error found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/RunMultipleAssignment2.output#L2-L8">Full source at GitHub</a>
<h2><a href="#3-4-灵活的参数和参数值" name="3-4-灵活的参数和参数值" class="anchor"><span class="anchor-link"></span></a>3.4 灵活的参数和参数值</h2>
<blockquote>
  <p>FromJavaToScala/Parameters.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def max(values: Int*) = values.foldLeft(values(0)) { Math.max }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Parameters.scala#L21">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Parameters.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">max(8, 2, 3)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Parameters.scala#L26">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Parameters.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">max(2, 5, 3, 7, 1, 6)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Parameters.scala#L32">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/ArgType.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def function(input: Int*): Unit = println(input.getClass)

function(1, 2, 3)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/ArgType.scala#L21-L23">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">class scala.collection.mutable.WrappedArray$ofInt</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/ArgType.output#L2">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/CantSendArray.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val numbers = Array(2, 5, 3, 7, 1, 6)
max(numbers) // type mismatch error</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter3/CantSendArray.scala#L23-L24">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">CantSendArray.scala:5: error: type mismatch;
 found   : Array[Int]
 required: Int
max(numbers) // type mismatch error
    ^
one error found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/RunCantSendArray.output#L2-L7">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Parameters.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val numbers = Array(2, 5, 3, 7, 1, 6)
max(numbers: _*)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Parameters.scala#L37-L38">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/DefaultValues.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def mail(destination: String = &quot;head office&quot;, mailClass: String = &quot;first&quot;): Unit =
  println(s&quot;sending to $destination by $mailClass class&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/DefaultValues.scala#L21-L22">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/DefaultValues.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">mail(&quot;Houston office&quot;, &quot;Priority&quot;)
mail(&quot;Boston office&quot;)
mail()</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/DefaultValues.scala#L26-L28">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">sending to Houston office by Priority class
sending to Boston office by first class
sending to head office by first class</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/DefaultValues.output#L2-L4">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Named.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">mail(mailClass = &quot;Priority&quot;, destination = &quot;Bahamas office&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Named.scala#L24">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Named.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">mail(mailClass = &quot;Priority&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Named.scala#L28">Full source at GitHub</a>
<h2><a href="#3-5-隐式参数" name="3-5-隐式参数" class="anchor"><span class="anchor-link"></span></a>3.5 隐式参数</h2>
<blockquote>
  <p>FromJavaToScala/ImplicitParameters.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Wifi(name: String) {
  override def toString: String = name
}

def connectToNetwork(user: String)(implicit wifi: Wifi): Unit = {
  println(s&quot;User: $user connected to WIFI $wifi&quot;)
}

def atOffice(): Unit = {
  println(&quot;--- at the office ---&quot;)
  implicit def officeNetwork: Wifi = new Wifi(&quot;office-network&quot;)
  val cafeteriaNetwork = new Wifi(&quot;cafe-connect&quot;)

  connectToNetwork(&quot;guest&quot;)(cafeteriaNetwork)
  connectToNetwork(&quot;Jill Coder&quot;)
  connectToNetwork(&quot;Joe Hacker&quot;)
}

def atJoesHome(): Unit = {
  println(&quot;--- at Joe&#39;s home ---&quot;)
  implicit def homeNetwork: Wifi = new Wifi(&quot;home-network&quot;)

  connectToNetwork(&quot;guest&quot;)(homeNetwork)
  connectToNetwork(&quot;Joe Hacker&quot;)
}

atOffice()
atJoesHome()</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/ImplicitParameters.scala#L21-L48">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">--- at the office ---
User: guest connected to WIFI cafe-connect
User: Jill Coder connected to WIFI office-network
User: Joe Hacker connected to WIFI office-network
--- at Joe&#39;s home ---
User: guest connected to WIFI home-network
User: Joe Hacker connected to WIFI home-network</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/ImplicitParameters.output#L2-L8">Full source at GitHub</a>
<h2><a href="#3-6-字符串和多行原始字符串" name="3-6-字符串和多行原始字符串" class="anchor"><span class="anchor-link"></span></a>3.6 字符串和多行原始字符串</h2>
<blockquote>
  <p>FromJavaToScala/MultiLine.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">  val str = &quot;&quot;&quot;In his famous inaugural speech, John F. Kennedy said
        &quot;And so, my fellow Americans: ask not what your country can do
	for you-ask what you can do for your country.&quot; He then proceeded
	to speak to the citizens of the World...&quot;&quot;&quot;
  println(str)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/MultiLine.scala#L21-L25">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">In his famous inaugural speech, John F. Kennedy said
        &quot;And so, my fellow Americans: ask not what your country can do 
	for you-ask what you can do for your country.&quot; He then proceeded 
	to speak to the citizens of the World...</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/MultiLine.output#L2-L5">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/MultiLine2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val str = &quot;&quot;&quot;In his famous inaugural speech, John F. Kennedy said
            	|&quot;And so, my fellow Americans: ask not what your country can do
            	|for you-ask what you can do for your country.&quot; He then proceeded
            	|to speak to the citizens of the World...&quot;&quot;&quot;.stripMargin
println(str)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/MultiLine2.scala#L21-L25">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">In his famous inaugural speech, John F. Kennedy said
&quot;And so, my fellow Americans: ask not what your country can do 
for you-ask what you can do for your country.&quot; He then proceeded 
to speak to the citizens of the World...</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/MultiLine2.output#L2-L5">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/StringInterpolation.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val message = s&quot;A discount of $discount% has been applied&quot;</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/StringInterpolation.scala#L23">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/StringInterpolation.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">var price = 90
val totalPrice = s&quot;The amount of discount is ${price * discount / 100} dollars&quot;</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/StringInterpolation.scala#L30-L31">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/StringInterpolation.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val totalPrice = s&quot;The amount of discount is $$${price * discount / 100}&quot;</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/StringInterpolation.scala#L40">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/StringInterpolation.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val discount = 10
var price = 100
val totalPrice =
  s&quot;The amount after discount is $$${price * (1 - discount / 100.0)}&quot;
println(totalPrice)

price = 50
println(totalPrice)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/StringInterpolation.scala#L47-L54">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">The amount after discount is $90.0
The amount after discount is $90.0</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/StringInterpolation.output#L6-L7">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/StringInterpolation.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val product = &quot;ticket&quot;
val price = 25.12
val discount = 10
println(s&quot;On $product $discount% saves $$${price * discount / 100.00}&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/StringInterpolation.scala#L60-L63">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">On ticket 10% saves $2.512</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/StringInterpolation.output#L11">Full source at GitHub</a>
<h2><a href="#3-9-操作符重载" name="3-9-操作符重载" class="anchor"><span class="anchor-link"></span></a>3.9 操作符重载</h2>
<blockquote>
  <p>FromJavaToScala/Complex.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Complex(val real: Int, val imaginary: Int) {
  def +(operand: Complex): Complex = {
    new Complex(real + operand.real, imaginary + operand.imaginary)
  }

  override def toString: String = {
    val sign = if (imaginary &lt; 0) &quot;&quot; else &quot;+&quot;
    s&quot;$real$sign${imaginary}i&quot;
  }
}

val c1 = new Complex(1, 2)
val c2 = new Complex(2, -3)
val sum = c1 + c2
println(s&quot;($c1) + ($c2) = $sum&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Complex.scala#L21-L35">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">(1+2i) + (2-3i) = 3-1i</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/Complex.output#L2">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Complex2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Complex(val real: Int, val imaginary: Int) {
  def +(operand: Complex): Complex = {
    println(&quot;Calling +&quot;)
    new Complex(real + operand.real, imaginary + operand.imaginary)
  }

  def *(operand: Complex): Complex = {
    println(&quot;Calling *&quot;)
    new Complex(
      real * operand.real - imaginary * operand.imaginary,
      real * operand.imaginary + imaginary * operand.real)
  }
  override def toString: String = {
    val sign = if (imaginary &lt; 0) &quot;&quot; else &quot;+&quot;
    s&quot;$real$sign${imaginary}i&quot;
  }
}

val c1 = new Complex(1, 4)
val c2 = new Complex(2, -3)
val c3 = new Complex(2, 2)
println(c1 + c2 * c3)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Complex2.scala#L21-L42">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Calling *
Calling +
11+2i</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/Complex2.output#L2-L4">Full source at GitHub</a>
<h2><a href="#3-10-scala-与-java-的差异" name="3-10-scala-与-java-的差异" class="anchor"><span class="anchor-link"></span></a>3.10 Scala 与 Java 的差异</h2>
<blockquote>
  <p>FromJavaToScala/SerialAssignments.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">var a = 1
var b = 2
a = b = 3 //Error</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter3/SerialAssignments.scala#L21-L23">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">SerialAssignments.scala:4: error: type mismatch;
 found   : Unit
 required: Int
a = b = 3
      ^
one error found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/RunSerialAssignments.output#L2-L7">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Equality.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val str1 = &quot;hello&quot;
val str2 = &quot;hello&quot;
val str3 = new String(&quot;hello&quot;)

println(str1 == str2) // Equivalent to Java&#39;s str1.equals(str2)
println(str1 eq str2) // Equivalent to Java&#39;s str1 == str2
println(str1 == str3)
println(str1 eq str3)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Equality.scala#L22-L29">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">true
true
true
false</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/Equality.output#L2-L5">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/OptionalSemicolon.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val list1 = new java.util.ArrayList[Int];
{
  println(&quot;Created list1&quot;)
}

val list2 = new java.util.ArrayList[Int] {
  println(&quot;Created list2&quot;)
}

println(list1.getClass)
println(list2.getClass)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/OptionalSemicolon.scala#L22-L32">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Created list1
Created list2
class java.util.ArrayList
class Main$$anon$2$$anon$1</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/OptionalSemicolon.output#L2-L5">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/AvoidExplicitReturn.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def check1 = true
def check2: Boolean = return true
def check3: Boolean = true
println(check1)
println(check2)
println(check3)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/AvoidExplitReturn.scala#L21-L26">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">true
true
true</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/AvoidExplitReturn.output#L2-L4">Full source at GitHub</a>
<h2><a href="#3-11-默认访问修饰符" name="3-11-默认访问修饰符" class="anchor"><span class="anchor-link"></span></a>3.11 默认访问修饰符</h2>
<blockquote>
  <p>FromJavaToScala/Access.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Microwave {
  def start(): Unit = println(&quot;started&quot;)
  def stop(): Unit = println(&quot;stopped&quot;)
  private def turnTable(): Unit = println(&quot;turning table&quot;)
}
val microwave = new Microwave
microwave.start() // OK</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/Access.scala#L21-L27">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Access.scala:9: error: method turnTable in class Microwave cannot be
accessed in this.Microwave
microwave.turnTable() //ERROR
          ^
one error found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/output/RunAccess.output#L2-L6">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/Protected.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Vehicle {
  protected def checkEngine() {}
}

class Car extends Vehicle {
  def start() { checkEngine() /*OK*/ }
  def tow(car: Car) {
    car.checkEngine() //OK
  }
  def tow(vehicle: Vehicle) {
    vehicle.checkEngine() //ERROR
  }
}

class GasStation {
  def fillGas(vehicle: Vehicle) {
    vehicle.checkEngine() //ERROR
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter3/Protected.scala#L21-L39">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Protected.scala:12: error: method checkEngine in class Vehicle cannot be
accessed in automobiles.Vehicle
 Access to protected method checkEngine not permitted because
 prefix type automobiles.Vehicle does not conform to
 class Car in package automobiles where the access take place
    vehicle.checkEngine() //ERROR
            ^
Protected.scala:17: error: method checkEngine in class Vehicle cannot be 
accessed in automobiles.Vehicle
 Access to protected method checkEngine not permitted because
 enclosing class GasStation in package automobiles is not a subclass of
 class Vehicle in package automobiles where target is defined
    vehicle.checkEngine() //ERROR
            ^
two errors found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/compileroutput/Protected.output#L2-L16">Full source at GitHub</a>
<blockquote>
  <p>FromJavaToScala/FineGrainedAccessControl.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">package society {

  package professional {
    class Executive {
      private[professional] var workDetails = null
      private[society] var friends = null
      private[this] var secrets = null

      def help(another: Executive): Unit = {
        println(another.workDetails)
        println(secrets)
        println(another.secrets) //ERROR
      }
    }

    class Assistant {
      def assist(anExec: Executive): Unit = {
        println(anExec.workDetails)
        println(anExec.friends)
      }
    }
  }

  package social {
    class Acquaintance {
      def socialize(person: professional.Executive) {
        println(person.friends)
        println(person.workDetails) // ERROR
      }
    }
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter3/FineGrainedAccessControl.scala#L18-L49">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">FineGrainedAccessControl.scala:12: error: value secrets is not a member of
society.professional.Executive
        println(another.secrets) //ERROR
                        ^
FineGrainedAccessControl.scala:28: error: variable workDetails in class 
Executive cannot be accessed in society.professional.Executive
        println(person.workDetails) // ERROR
                       ^
two errors found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter3/compileroutput/FineGrainedAccessControl.output#L2-L10">Full source at GitHub</a>
</div>
<div>
<a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/master/src/paradox/chapter-03/index.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../chapter-02/index.html" title="第2章——体验Scala" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
第2章——体验Scala
</span>
</div>
</a>
<a href="../chapter-04/index.html" title="第4章——善用对象" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
第4章——善用对象
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
